package ext.generic.doc;

import com.ptc.core.components.forms.FormProcessingStatus;
import com.ptc.core.components.forms.FormResult;

import com.ptc.core.components.util.FeedbackMessage;
import com.ptc.core.ui.resources.FeedbackType;

import java.util.*;

import java.sql.Timestamp;

import java.io.*;

import com.ptc.netmarkets.util.beans.NmCommandBean;
import com.ptc.netmarkets.util.misc.*;
import com.ptc.netmarkets.model.*;

import com.ptc.windchill.enterprise.wip.WIPUtils;
import com.ptc.wvs.server.util.Util;

//import ext.generic.esignature.util.PdfSignatureUtil;

import wt.fc.*;

import wt.change2.WTChangeOrder2;
import wt.content.*;

import wt.util.*;

import wt.doc.WTDocument;

import wt.epm.EPMDocument;
import wt.epm.EPMDocumentMaster;
import wt.epm.structure.EPMStructureHelper;
import wt.epm.structure.EPMReferenceLink;

import wt.vc.*;
import wt.vc.config.LatestConfigSpec;

import wt.query.*;
import wt.representation.Representable;
import wt.representation.Representation;
import wt.representation.RepresentationHelper;

import wt.iba.value.IBAHolder;

import wt.method.RemoteMethodServer;
import wt.method.RemoteAccess;

import wt.fv.master.RedirectDownload;

import wt.session.SessionServerHelper;

import ext.com.iba.IBAUtil;

import wt.doc.WTDocumentMaster;

import wt.fc.collections.WTArrayList;

import wt.fc.collections.WTCollection;

import wt.identity.DisplayIdentity;

import wt.identity.IdentityFactory;

import wt.part.PartDocHelper;

import wt.part.WTPart;

import wt.part.WTPartDescribeLink;

import wt.part.WTPartReferenceLink;

import wt.part.WTProductInstance2;

import wt.session.SessionHelper;

import wt.vc.wip.WorkInProgressHelper;

/**
 * 通用的文档处理方法类
 */

public class GenericDocCommands implements RemoteAccess
{
    public static boolean VERBOSE = false;
    public static WTProperties wtProperties;
    public static String CLASSNAME = "";
    public static String info_separator = "##";
    public static String info_sub_separator = "~~";

    static
    {
        CLASSNAME = GenericDocCommands.class.getName();
        try
        {
            wtProperties = WTProperties.getLocalProperties();
            VERBOSE = wtProperties.getProperty("ext.generic.doc.verbose", false);
        }
        catch (java.io.IOException ioe)
        {
            ioe.printStackTrace();
        }
    }

    /**
     *根据用户选择的文档或CAD文档,获取这些需要下载对象的oid
     */
    public static String getDownloadObjectOids(NmCommandBean nmcommandbean)
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".getDownloadObjectOids()");

        String oids = "";
        if (!RemoteMethodServer.ServerFlag)
        {
            String method = "getDownloadObjectOids";
            try
            {
                oids = (String) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new Class[]
                            { NmCommandBean.class }, new Object[]
                            { nmcommandbean });
            }
            catch (Exception exp)
            {
                exp.printStackTrace();
            }
            return oids;
        }
        try
        {
            ArrayList arraylist1 = nmcommandbean.getSelectedOidForPopup();
            Iterator iterator = arraylist1.iterator();
            do
            {
                if (!iterator.hasNext())
                {
                    break;
                }
                Object obj = iterator.next();
                NmOid nmoid = NmCommandBean.getOidFromObject(obj);
                if (nmoid.isA(FormatContentHolder.class))
                {
                    if (oids.length() <= 0)
                        oids = nmoid.toString();
                    else
                        oids = oids + info_separator + nmoid.toString();
                }
            }
            while (true);
        }
        catch (Exception exp)
        {
            exp.printStackTrace();
        }
        if (VERBOSE)
        {
            System.out.println(" download objects oids=" + oids);
            System.out.println("<<<" + CLASSNAME + ".getDownloadObjectOids()");
        }
        return oids;
    }

    /**
     *根据用户选择的文档或CAD文档,获取对应的主文件或附件的下载地址;对于CAD图档,可以获取其参考文档的信息;
     */
    public static HashMap getDownloadFilesInfo(String oids, Boolean includeAttachment, Boolean includeReferences)
    {
        if (VERBOSE)
        {
            System.out.println(">>>" + CLASSNAME + ".getDownloadFilesInfo()");
        }
        HashMap info = new HashMap();
        if (!RemoteMethodServer.ServerFlag)
        {
            String method = "getDownloadFilesInfo";
            try
            {
                info = (HashMap) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new Class[]
                            { String.class, Boolean.class, Boolean.class }, new Object[]
                            { oids, includeAttachment, includeReferences });
            }
            catch (Exception exp)
            {
                exp.printStackTrace();
            }
            return info;
        }
        if (VERBOSE)
            System.out.println("	oids=" + oids);
        //对于每一个文件来说,其所需的信息:编号~~文件名~~电子签名信息(角色名1=用户ID,签字日期;角色名2=用户ID,签字日期)~~其它信息

        try
        {
            String aOids[] = oids.split(info_separator);
            ReferenceFactory rf = new ReferenceFactory();
            for (int i = 0; i < aOids.length; i++)
            {
                String oid = aOids[i];
                if (VERBOSE)
                    System.out.println("	oid=" + oid);
                FormatContentHolder contentHolder = (FormatContentHolder) rf.getReference(oid).getObject();
                getDownloadInfo(contentHolder, includeAttachment, info);
                if ((contentHolder instanceof EPMDocument) && includeReferences)
                {
                    if (VERBOSE)
                        System.out.println("	start getting the download info of reference cad documents.");
                    QueryResult references = getReferenceCADDocuments((EPMDocument) contentHolder);
                    while (references.hasMoreElements())
                    {
                        EPMDocument ref = (EPMDocument) references.nextElement();
                        getDownloadInfo(ref, includeAttachment, info);
                    }
                    if (VERBOSE)
                        System.out.println("	end of getting the download info of reference cad documents.");
                }
            }
        }
        catch (Exception exp)
        {
            exp.printStackTrace();
        }
        if (VERBOSE)
        {
            System.out.println(" download info=" + info);
            System.out.println("<<<" + CLASSNAME + ".getDownloadFilesInfo()");
        }
        return info;
    }

    /**
     *根据用户选择的文档或CAD文档,获取对应的原始打印的文件(没有经过电子签名打印的文件）的下载地址;
     */
    public static HashMap getDownloadSourcePrintFilesInfo(String oids)
    {
        if (VERBOSE)
        {
            System.out.println(">>>" + CLASSNAME + ".getDownloadSourcePrintFilesInfo()");
        }
        HashMap info = new HashMap();
        if (!RemoteMethodServer.ServerFlag)
        {
            String method = "getDownloadSourcePrintFilesInfo";
            try
            {
                info = (HashMap) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new Class[]
                            { String.class }, new Object[]
                            { oids });
            }
            catch (Exception exp)
            {
                exp.printStackTrace();
            }
            return info;
        }
        if (VERBOSE)
            System.out.println("    oids=" + oids);
        //对于每一个文件来说,其所需的信息:编号~~文件名~~电子签名信息(角色名1=用户ID,签字日期;角色名2=用户ID,签字日期)~~其它信息

        try
        {
            String aOids[] = oids.split(info_separator);
            ReferenceFactory rf = new ReferenceFactory();
            for (int i = 0; i < aOids.length; i++)
            {
                String oid = aOids[i];
                if (VERBOSE)
                    System.out.println("    oid=" + oid);
                FormatContentHolder contentHolder = (FormatContentHolder) rf.getReference(oid).getObject();
                getDownloadSourcePrintFileInfo(contentHolder, info);
            }
        }
        catch (Exception exp)
        {
            exp.printStackTrace();
        }
        if (VERBOSE)
        {
            System.out.println(" download source print file info=" + info);
            System.out.println("<<<" + CLASSNAME + ".getDownloadSourcePrintFilesInfo()");
        }
        return info;
    }

    /**
     *根据用户选择的文档或CAD文档,获取对应的原始打印的文件(没有经过电子签名打印的文件）的下载地址;
     */
    public static HashMap getDownloadInfo(FormatContentHolder contentHolder, Boolean includeAttachment, HashMap info)
    {
        if (VERBOSE)
        {
            System.out.println(">>>" + CLASSNAME + ".getDownloadInfo()");
        }
        //对于每一个文件来说,其所需的信息:编号~~文件名~~电子签名信息(角色名1=用户ID,签字日期;角色名2=用户ID,签字日期)~~其它信息
        try
        {
            HashMap thisFileInfo = new HashMap();
            HashMap fileSignInfo = new HashMap();
            HashMap versionsSignInfo = new HashMap();

            String number = "";
            if (contentHolder instanceof EPMDocument)
            {
                number = ((EPMDocument) contentHolder).getNumber(); //获取图号？
            }
            else if (contentHolder instanceof WTDocument)
            {
                number = ((WTDocument) contentHolder).getNumber();
            }
            else
                number = "---";
            if (info.get(number) != null)
            {
                if (VERBOSE)
                    System.out.println("	图文档(" + contentHolder.getIdentity() + ")的下载信息已经获取过,不需要重复获取.");
                return info;
            }

            //获取签审信息
            String signInfo = getSignatureInfo(contentHolder);
            if (signInfo == null || signInfo.length() <= 0)
                signInfo = "---";
            String barCode = "---";
            //获取对象主要文件的下载地址
            String curVersionFileInfo = "";
            contentHolder = (FormatContentHolder) ContentHelper.service.getContents(contentHolder);
            ApplicationData primary = (ApplicationData) contentHolder.getPrimary();
            if (primary != null)
            {
                String downloadURL[] = getDownloadURL(contentHolder, primary);
                String fileInfo = downloadURL[0] + info_sub_separator + downloadURL[1] + info_sub_separator + signInfo + info_sub_separator + barCode;
                curVersionFileInfo = fileInfo;
                fileSignInfo.put(downloadURL[0], fileInfo);
            }
            //获取附件的下载地址
            if (includeAttachment.booleanValue())
            {
                QueryResult attachments = ContentHelper.service.getContentsByRole(contentHolder, ContentRoleType.SECONDARY);
                while (attachments.hasMoreElements())
                {
                    ContentItem attachment = (ContentItem) attachments.nextElement();
                    if (attachment instanceof ApplicationData)
                    {
                        String downloadURL[] = getDownloadURL(contentHolder, (ApplicationData) attachment);
                        String fileInfo = downloadURL[0] + info_sub_separator + downloadURL[1] + info_sub_separator + signInfo + info_sub_separator + barCode;
                        fileSignInfo.put(downloadURL[0], fileInfo);
                    }
                }
            }

            //记录缓存中
            thisFileInfo.put("fileSignInfo", fileSignInfo);
            thisFileInfo.put("versionsSignInfo", versionsSignInfo);
            info.put(number, thisFileInfo);

        }
        catch (Exception exp)
        {
            exp.printStackTrace();
        }
        if (VERBOSE)
        {
            System.out.println(" download info=" + info);
            System.out.println("<<<" + CLASSNAME + ".getDownloadInfo()");
        }
        return info;
    }

    /**
     *根据用户选择的文档或CAD文档,获取对应的可供打印的文件的下载地址
     */
    public static HashMap getDownloadSourcePrintFileInfo(FormatContentHolder contentHolder, HashMap info)
    {
        if (VERBOSE)
        {
            System.out.println(">>>" + CLASSNAME + ".getDownloadSourcePrintFileInfo()");
        }
        //对于每一个文件来说,其所需的信息:编号~~文件名~~电子签名信息(角色名1=用户ID,签字日期;角色名2=用户ID,签字日期)~~其它信息
        try
        {
            HashMap thisFileInfo = new HashMap();
            HashMap fileSignInfo = new HashMap();

            String number = "";
            if (contentHolder instanceof EPMDocument)
            {
                number = ((EPMDocument) contentHolder).getNumber(); //获取图号？
            }
            else if (contentHolder instanceof WTDocument)
            {
                number = ((WTDocument) contentHolder).getNumber();
            }
            else
                number = "---";
            if (info.get(number) != null)
            {
                if (VERBOSE)
                    System.out.println("    图文档(" + contentHolder.getIdentity() + ")的下载信息已经获取过,不需要重复获取.");
                return info;
            }

            //获取签审信息
            String signInfo = getSignatureInfo(contentHolder);
            if (signInfo == null || signInfo.length() <= 0)
                signInfo = "---";
            //获取对象主要文件的下载地址
            String curVersionFileInfo = "";

            //ApplicationData primary = (ApplicationData) contentHolder.getPrimary();
//            Vector vecsourcePrintFile = PdfSignatureUtil.getSourcePrintFiles(contentHolder);
            Vector vecsourcePrintFile = getSourcePrintFiles(contentHolder);
            
            for(int i=0;i<vecsourcePrintFile.size();i++){
            	ApplicationData sourcePrintFile=(ApplicationData) vecsourcePrintFile.get(i);
            if (sourcePrintFile != null)
            {
                FormatContentHolder rep = (FormatContentHolder) sourcePrintFile.getHolderLink().getContentHolder();
                String downloadURL[] = getDownloadURL(rep, sourcePrintFile);
                String fileInfo = downloadURL[0] + info_sub_separator + downloadURL[1] + info_sub_separator + signInfo;
                curVersionFileInfo = fileInfo;
                fileSignInfo.put(downloadURL[0], fileInfo);
            }
            //记录缓存中
            thisFileInfo.put("fileSignInfo", fileSignInfo);
            info.put(number, thisFileInfo);
            }
        }
        catch (Exception exp)
        {
            exp.printStackTrace();
        }
        if (VERBOSE)
        {
            System.out.println(" download source print file info=" + info);
            System.out.println("<<<" + CLASSNAME + ".getDownloadSourcePrintFileInfo()");
        }
        return info;
    }


    /**
     *获取文件内容的下载地址
     */
    public static String[] getDownloadURL(FormatContentHolder contentHolder, ApplicationData contentItem) throws WTException
    {
        String fileName = contentItem.getFileName();
        if (fileName.equals("{$CAD_NAME}"))
        {
            fileName = ((wt.epm.EPMDocument) contentHolder).getCADName();
        }
        String url = "";
        try
        {
            url = RedirectDownload.getPreferredURL(contentItem, contentHolder).toExternalForm();
        }
        catch (IOException ioe)
        {
            throw new WTException(ioe);
        }

        String result[] =
        { fileName, url };
        return result;
    }

    /**
     *获取对象的流程签名信息
     */
    public static String getSignatureInfo(FormatContentHolder contentHolder)
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".getSignInfo()---content Holder=" + ((WTObject) contentHolder).getDisplayIdentity());
        String signInfoStr = "";

        try
        {
            /*
				Hashtable signInfo= ext.gedi.workflow.GediWFUtil.queryElectronicSignature((WTObject)contentHolder, activityNames);
			if(signInfo!=null)
			{
				//设计=g1234 2010-12-01##校核=g2345 2010-12-03##会签=g3456 2010-12-04;g3457 2010-12-04##批准=g5765 2010-12-05
			}
			*/
            signInfoStr = "Creator=" + ((Iterated) contentHolder).getCreatorFullName() + " " + ((Iterated) contentHolder).getPersistInfo().getCreateStamp();
        }
        catch (Exception exp)
        {
            exp.printStackTrace();
        }

        if (VERBOSE)
        {
            System.out.println("	sign info string=" + signInfoStr);
            System.out.println("<<<" + CLASSNAME + "getSignInfo()---content Holder=" + ((WTObject) contentHolder).getDisplayIdentity());
        }

        return signInfoStr;
    }

    /**
     *获取所有版本签审信息
     *@param includeAllVersionsSignInfo
     */
    public static Hashtable getSignatureInfoForPdfPrint(FormatContentHolder contentHolder, boolean includeAllVersionsSignInfo)
    {
        if (VERBOSE)
        {
            System.out.println(">>>" + CLASSNAME + ".getSignatureInfoForPdfPrint()---content Holder=" + ((WTObject) contentHolder).getDisplayIdentity());
            System.out.println("	includeAllVersionsSignInfo=" + includeAllVersionsSignInfo);
        }
        Hashtable signInfo = new Hashtable();
        signInfo = getOneVersionSignatureInfoForPdfPrint(contentHolder);
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".getSignatureInfoForPdfPrint()---content Holder=" + ((WTObject) contentHolder).getDisplayIdentity());
        return signInfo;
    }

    /**
     *获取对象的流程签名信息
     */
    public static Hashtable getOneVersionSignatureInfoForPdfPrint(FormatContentHolder contentHolder)
    {
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".getOneVersionSignatureInfoForPdfPrint()---content Holder=" + ((WTObject) contentHolder).getDisplayIdentity());
        Hashtable newSignInfo = new Hashtable();
        try
        {
            //Hashtable signInfo= ext.generic.workflow.WorkflowUtil.queryElectronicSignature((WTObject)contentHolder);
            //添加版本信息
            String versionId = VersionControlHelper.getVersionDisplayIdentifier((Versioned) contentHolder).toString();
            newSignInfo.put("版本", versionId);
        }
        catch (Exception exp)
        {
            exp.printStackTrace();
        }

        if (VERBOSE)
        {
            System.out.println("	sign info=" + newSignInfo);
            System.out.println("<<<" + CLASSNAME + "getOneVersionSignatureInfoForPdfPrint()---content Holder=" + ((WTObject) contentHolder).getDisplayIdentity());
        }

        return newSignInfo;
    }

    /**
     *更新文件内容
     * @param holder content holder,即文档/CAD图档/或变更对象等包含文件内容的对象
     * @param fileName 新文件名称
     * @param uploadPath 新文件所在路径
     * @param is    新文件流
     * @param isPrimary 是否是主文件
     * @return 更新结果
     * @throws WTException
     */
    public static Boolean updateContent(FormatContentHolder holder, String fileName, String uploadPath, FileInputStream is, boolean isPrimary) throws WTException
    {
        if (VERBOSE)
        {
            System.out.println(">>>" + CLASSNAME + ".updateContent()");
        }
        Boolean result = new Boolean(false);
        boolean flag = SessionServerHelper.manager.setAccessEnforced(false);

        try
        {
            holder = (FormatContentHolder) ContentHelper.service.getContents(holder);
            if (isPrimary)
            {
                ApplicationData primary = (ApplicationData) holder.getPrimary();
                if (primary != null)
                {
                    primary.setUploadedFromPath(uploadPath);
                    primary = ContentServerHelper.service.updatePrimary(holder, primary, is);
                    if (VERBOSE)
                        System.out.println("	the primary exists and been updated.");
                }
                else
                {
                    ApplicationData appData = ApplicationData.newApplicationData(holder);
                    appData.setFileName(fileName);
                    appData.setRole(ContentRoleType.PRIMARY);
                    appData.setUploadedFromPath(uploadPath);
                    appData = setDataFormat(appData);
                    appData = ContentServerHelper.service.updatePrimary(holder, appData, is);
                    if (VERBOSE)
                        System.out.println("	the primary content doesn't exists and been added.");
                }
                holder = ContentServerHelper.service.updateHolderFormat(holder);
                if (VERBOSE)
                    System.out.println("	content holder's format has been updated.");
            }
            else
            {
                QueryResult attachments = ContentHelper.service.getContentsByRole(holder, ContentRoleType.SECONDARY);
                boolean bExists = false;
                while (attachments.hasMoreElements())
                {
                    ContentItem attachment = (ContentItem) attachments.nextElement();
                    if (attachment instanceof ApplicationData)
                    {
                        String fileName2 = ((ApplicationData) attachment).getFileName();
                        if (fileName.equals(fileName2))
                        {
                            bExists = true;
                            ((ApplicationData) attachment).setUploadedFromPath(uploadPath);
                            attachment = ContentServerHelper.service.updateContent(holder, ((ApplicationData) attachment), is, false);
                            if (VERBOSE)
                                System.out.println("	the attachment exists and been updated.");
                        }
                    }
                }
                if (!bExists)
                {
                    ApplicationData appData = ApplicationData.newApplicationData(holder);
                    appData.setFileName(fileName);
                    appData.setRole(ContentRoleType.SECONDARY);
                    appData.setUploadedFromPath(uploadPath);
                    appData = setDataFormat(appData);
                    appData = ContentServerHelper.service.updateContent(holder, appData, is);
                    if (VERBOSE)
                        System.out.println("	the attachment doesn't exists and been added.");
                }
            }

            result = new Boolean(true);
        }
        catch (java.beans.PropertyVetoException pve)
        {
            throw new WTException(pve);
        }
        catch (IOException ioe)
        {
            throw new WTException(ioe);
        }
        finally
        {
            SessionServerHelper.manager.setAccessEnforced(flag);
        }
        if (VERBOSE)
        {
            System.out.println("<<<" + CLASSNAME + ".updateContent()---result=" + result);
        }
        return result;
    }

    /**
     *设置文件的格式
     * @param appData 主文件或者附件对象
     */
    public static ApplicationData setDataFormat(ApplicationData appData) throws WTException
    {
        String fileName = appData.getFileName();
        //获取其扩展名
        int index = fileName.lastIndexOf(".");
        if (index <= 0)
        {
            return appData;
        }
        else
        {
            String extension = "";
            extension = fileName.substring(index + 1);
            extension = extension.toUpperCase();
            DataFormat dataFormat = null;
            try
            {
                dataFormat = ContentHelper.service.getFormatByName(extension);
            }
            catch (Exception exp)
            {
                dataFormat = ContentHelper.service.getFormatByName("Unknown");
            }

            if (dataFormat != null)
            {
                DataFormatReference ref = DataFormatReference.newDataFormatReference(dataFormat);
                try
                {
                    appData.setFormat(ref);
                    if (VERBOSE)
                        System.out.println("	set the data format=" + extension);
                }
                catch (WTPropertyVetoException wpve)
                {
                    throw new WTException(wpve);
                }
            }
            return appData;
        }
    }

    /**
     *根据编号获取最新版本的CAD图档
     */
    public static EPMDocument getLatestEPMDocByNumber(String epmDocNumber) throws WTException
    {
        if (!RemoteMethodServer.ServerFlag)
        {
            if (VERBOSE)
                System.out.println(">>>client>>>" + CLASSNAME + ".getLatestEPMDocByNumber()");
            String method = "getLatestEPMDocByNumber";
            try
            {
                return (EPMDocument) RemoteMethodServer.getDefault().invoke(method, CLASSNAME, null, new Class[]
                        { String.class }, new Object[]
                        { epmDocNumber });
            }
            catch (Exception exp)
            {
                exp.printStackTrace();
            }
        }
        if (VERBOSE)
            System.out.println(">>>" + CLASSNAME + ".getLatestEPMDocByNumber()");
        EPMDocument doc = null;
        QuerySpec qs = new QuerySpec(EPMDocumentMaster.class);
        SearchCondition sc = new SearchCondition(EPMDocumentMaster.class, "number", SearchCondition.EQUAL, epmDocNumber);
        qs.appendSearchCondition(sc);
        QueryResult qr = PersistenceHelper.manager.find(qs);
        while (qr.hasMoreElements())
        {
            EPMDocumentMaster master = (EPMDocumentMaster) qr.nextElement();
            doc = getLatestEPMDocByMaster(master);
            break;
        }
        if (VERBOSE)
            System.out.println("<<<" + CLASSNAME + ".getLatestEPMDocByNumber()");
        return doc;
    }

    /**
     *根据CAD图档主数据(master)获取最新版本的CAD图档
     * @param master
     * @return
     * @throws WTException
     */
    public static EPMDocument getLatestEPMDocByMaster(EPMDocumentMaster master) throws WTException
    {
        if (master == null)
        {
            return null;
        }
        boolean flag = false;
        Iterated iter = null;
        // 获取该master对应的所有的epm对象
        QueryResult queryresult = VersionControlHelper.service.allIterationsOf(master);
        while (queryresult.hasMoreElements() && (!flag))
        {
            iter = (Iterated) (queryresult.nextElement());
            flag = iter.isLatestIteration();
        }
        return (EPMDocument) iter;
    }

    /**
     *根据CAD图档获取参考的CAD图档
     */
    public static QueryResult getReferenceCADDocuments(EPMDocument target) throws WTException
    {
        QueryResult qr = new QueryResult();
        QuerySpec qs = new QuerySpec(EPMReferenceLink.class);
        LatestConfigSpec configSpec = new LatestConfigSpec();
        try
        {
            qr = EPMStructureHelper.service.navigateReferencesToIteration(target, qs, true, configSpec);
        }
        catch (WTException wtexception)
        {
            wtexception.printStackTrace();
        }
        if (VERBOSE)
            System.out.println("	found " + qr.size() + " reference cad documents.");
        return qr;
    }

    /**
     *根据文档获取其关联的CAD图档
     * @param doc
     * @return
     * @throws WTException
     */
    /**
     
    public static Vector getRelatedCADDocuments(WTDocument doc) throws WTException
    {
        QueryResult queryresult = PersistenceHelper.manager.navigate(doc, WTDocToCADDocLink.ASSOCIATED_CADDOC_ROLE, WTDocToCADDocLink.class, true);
        return queryresult.getObjectVectorIfc().getVector();
    }
	*/
    /**
     *根据文档以及CAD图档获取其关联关系
     * @param doc
     * @param cad
     * @return
     * @throws WTException
     */
    /**
    public static Vector getRelatedCADDocLink(WTDocument doc, EPMDocument cad) throws WTException
    {
        QueryResult qr = PersistenceHelper.manager.find(WTDocToCADDocLink.class, doc, WTDocToCADDocLink.ASSOCIATED_DOC_ROLE, cad);
        System.out.println("    doc-cad links count=" + qr.size());
        return qr.getObjectVectorIfc().getVector();
    }
	*/
    /**
     *删除文档与用户选择的CAD图档之间的关联
     * @param nmcommandbean
     * @param flag
     * @return
     * @throws WTException
     */
    /**
    public static FormResult deleteRelationDocCAD(NmCommandBean nmcommandbean) throws WTException
    {
        Object obj = new WTArrayList();
        WTArrayList wtarraylist = new WTArrayList();
        Vector vector = new Vector();
        FormResult formresult = new FormResult();
        formresult.setStatus(FormProcessingStatus.SUCCESS);
        ArrayList arraylist = nmcommandbean.getSelected();
        WTDocument wtdocument = (WTDocument) nmcommandbean.getPrimaryOid().getWtRef().getObject();

        if (WIPUtils.enableableObject(wtdocument).booleanValue() && !WorkInProgressHelper.isWorkingCopy(wtdocument))
            wtdocument = (WTDocument) WorkInProgressHelper.service.workingCopyOf(wtdocument);
        wtarraylist.add(wtdocument);
        if (wtarraylist.size() > 0 && arraylist != null && arraylist.size() > 0)
        {
            for (int i = 0; i < arraylist.size(); i++)
            {
                NmContext nmcontext = (NmContext) arraylist.get(i);
                Persistable persistable = nmcontext.getTargetOid().getWtRef().getObject();
                if (persistable instanceof EPMDocument)
                {
                    //去掉文档和CAD图档的关联
                    EPMDocument cad = (EPMDocument) persistable;
                    Vector links= getRelatedCADDocLink(wtdocument, cad);
                    if(links!=null && links.size()>0)
                    {
                        for(int j=0; j<links.size(); j++)
                        {
                            PersistenceServerHelper.manager.remove((Persistable)links.elementAt(j));
                            System.out.println("删除CAD图档:" + cad.getIdentity() + "和文档" + wtdocument.getIdentity() + "关联");
                        }
                    }
                }
            }

        }
        if (vector.size() != 0)
        {
            Locale locale = SessionHelper.getLocale();
            formresult.addFeedbackMessage(getRemoveFbMsg(FeedbackType.FAILURE, vector, locale));
            formresult.setStatus(FormProcessingStatus.SUCCESS);
        }
        return formresult;
    }
	*/
    public static FeedbackMessage getRemoveFbMsg(FeedbackType feedbacktype, List list, Locale locale) throws WTException
    {
        String s = WTMessage.getLocalizedMessage("com.ptc.netmarkets.util.beans.beansResource", "Remove_Action_Partially_Failed", null);
        String s1 = WTMessage.getLocalizedMessage("com.ptc.netmarkets.util.beans.beansResource", "Remove_Action_Partially_Failed_Msg1", null);
        return createFeedbackMessage(FeedbackType.FAILURE, locale, s, s1, null, list);
    }

    /**
     *生成反馈信息
     * @param feedbacktype
     * @param locale
     * @param s
     * @param s1
     * @param s2
     * @param list
     * @return
     * @throws WTException
     */
    public static FeedbackMessage createFeedbackMessage(FeedbackType feedbacktype, Locale locale, String s, String s1, String s2, List list) throws WTException
    {
        StringBuffer stringbuffer = new StringBuffer(s1);
        if (list.size() > 0)
        {
            stringbuffer.append("\n");
        }
        for (int i = 0; i < list.size(); i++)
        {
            Object obj = list.get(i);
            DisplayIdentity displayidentity = IdentityFactory.getDisplayIdentity(obj);
            stringbuffer.append("\n   ");
            stringbuffer.append(displayidentity.getLocalizedMessage(locale));
        }

        if (s2 != null && s2.length() > 0)
        {
            stringbuffer.append("\n\n");
            stringbuffer.append(s2);
        }
        FeedbackMessage feedbackmessage = new FeedbackMessage(feedbacktype, locale, s, null, new String[]
                { stringbuffer.toString() });
        return feedbackmessage;
    }
    
    /**
     *获取供电子签名打印的原始pdf文件；普通文档、CAD图档、变更通告获取的规则不相同
     */
    public static Vector getSourcePrintFiles(ContentHolder object) throws WTException
    {
        if (VERBOSE)
            System.out.println("	>>>" + CLASSNAME + ".getSourcePrintFile()");
        //获得文档对象的表示法对象
        Vector sourceFiles = new Vector();
        ApplicationData sourceFile = null;
        if (object instanceof WTDocument) //对于普通文档，从其可视化数据数据中获取pdf文件作为打印的原始文件
        {
            Representation representation = RepresentationHelper.service.getDefaultRepresentation((Representable) object);
            boolean primaryContentIsPdf = primaryContentIsPdf((WTDocument) object);
            if (representation == null && !primaryContentIsPdf)
            {
                System.out.println("	没有可视化数据,不进行电子签名打印.");
                return null;
            }
            else if (representation != null)
            {
                try
                {
                    representation = (Representation) ContentHelper.service.getContents(representation);
                }
                catch (Exception exp)
                {
                    throw new WTException(exp);
                }

                Vector contents = ContentHelper.getContentListAll(representation);
                if (VERBOSE)
                    System.out.println("	contents count=" + contents.size());
                for (int i = 0; i < contents.size(); i++)
                {
                    ContentItem contentItem = (ContentItem) contents.elementAt(i);
                    if (contentItem instanceof ApplicationData)
                    {
                        String fileName = ((ApplicationData) contentItem).getFileName();
                        if (VERBOSE)
                            System.out.println("	representation fileName=" + fileName);
                        if (fileName.toUpperCase().endsWith(".PDF"))
                        {
                            sourceFiles.add(contentItem);
                            if (VERBOSE)
                                System.out.println("	got one source representation pdf file");
                        }
                    }
                }
            }
            else if (primaryContentIsPdf)
            {
                ContentHolder contentHolder = (ContentHolder) object;
                try
                {
                    contentHolder = ContentHelper.service.getContents(contentHolder);
                }
                catch (Exception e)
                {
                    throw new WTException(e);
                }
                Vector contentListAllVc = ContentHelper.getContentListAll(contentHolder);
                for (int i = 0; i < contentListAllVc.size(); i++)
                {
                    ContentItem item = (ContentItem) contentListAllVc.elementAt(i);
                    ContentRoleType roleType = item.getRole();
                    if (item instanceof ApplicationData)
                    {
                        if (roleType.equals(ContentRoleType.PRIMARY))
                        {
                            sourceFiles.add(item);
                            if (VERBOSE)
                                System.out.println("	got one source pdf file from WTDocument primary content");
                        }
                    }
                }
            }

        }
        //对于CAD图档，从其附件中获取与主文件同名的pdf文件作为打印的原始文件；如果没有，则从可视化数据中获取pdf文件
        else if (object instanceof EPMDocument)
        {
            if (VERBOSE)
                System.out.println("	start get source print file for EPMDocument..");
            try
            {
                object = ContentHelper.service.getContents((EPMDocument) object);
            }
            catch (Exception exp)
            {
                throw new WTException(exp);
            }
            ApplicationData primary = (ApplicationData) ContentHelper.getPrimary((EPMDocument) object);
            String primaryFileName = primary.getFileName();
            if (VERBOSE)
                System.out.println("	got primary file=" + primaryFileName);
            if (primaryFileName.equals("{$CAD_NAME}"))
                primaryFileName = ((EPMDocument) object).getCADName();
            String pdfFileName = Util.removeExtension(primaryFileName) + ".pdf";
            if (VERBOSE)
                System.out.println("	start find the source print file=" + pdfFileName);
            Vector contents = ContentHelper.getContentList((EPMDocument) object);
            if (VERBOSE)
                System.out.println("	contents count=" + contents.size());
            for (int i = 0; i < contents.size(); i++)
            {
                ContentItem contentItem = (ContentItem) contents.elementAt(i);
                if (contentItem instanceof ApplicationData)
                {
                    String fileName = ((ApplicationData) contentItem).getFileName();
                    if (VERBOSE)
                        System.out.println("	attachment file Name=" + fileName);
                    if (fileName.equals(pdfFileName))
                    {
                        sourceFiles.add(contentItem);
                        if (VERBOSE)
                            System.out.println("	got source pdf file");
                    }
                }
            }
            if (sourceFiles.size() <= 0) //如果附件中没有pdf文件，则从可视化文件中获取
            {
                Representation representation = RepresentationHelper.service.getDefaultRepresentation((Representable) object);
                if (representation == null)
                {
                    System.out.println("    没有可视化数据,不进行电子签名打印.");
                }
                else
                {
                    try
                    {
                        representation = (Representation) ContentHelper.service.getContents(representation);
                    }
                    catch (Exception exp)
                    {
                        throw new WTException(exp);
                    }

                    Vector contents2 = ContentHelper.getContentListAll(representation);
                    if (VERBOSE)
                        System.out.println("    contents count=" + contents.size());
                    for (int i = 0; i < contents2.size(); i++)
                    {
                        ContentItem contentItem = (ContentItem) contents2.elementAt(i);
                        if (contentItem instanceof ApplicationData)
                        {
                            String fileName = ((ApplicationData) contentItem).getFileName();
                            if (VERBOSE)
                                System.out.println("    representation fileName=" + fileName);
                            if (fileName.toUpperCase().endsWith(".PDF"))
                            {
                                sourceFiles.add(contentItem);
                                if (VERBOSE)
                                    System.out.println("    got source representation pdf file");
                            }
                        }
                    }
                }
            }
        }
        else if (object instanceof WTChangeOrder2)
        {
            //add the codes
        }
        if (VERBOSE)
            System.out.println("	<<<" + CLASSNAME + ".getSourcePrintFile()");
        return sourceFiles;
    }
    
    /**
     * 判断普通文档主文件是否是PDF
     *
     * @param doc 文档
     * @return boolean 结果
     **/
    public static boolean primaryContentIsPdf(WTDocument doc) throws WTException
    {
        ContentHolder contentHolder = (ContentHolder) doc;
        try
        {
            QueryResult contents = ContentHelper.service.getContentsByRole(doc, ContentRoleType.PRIMARY);
            if (VERBOSE)
                System.out.println("    the count of  primary content items=" + contents.size());
            if (contents.hasMoreElements())
            {
                ContentItem item = (ContentItem) contents.nextElement();
                if (item instanceof ApplicationData)
                {
                    ApplicationData data = (ApplicationData) item;
                    String primaryContentName = data.getFileName();
                    if (primaryContentName.toUpperCase().endsWith(".PDF"))
                    {
                        if (VERBOSE)
                            System.out.println("    primaryContentIsPdf : true  ");
                        return true;
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new WTException(e);
        }

        if (VERBOSE)
            System.out.println("	primaryContentIsPdf : false	");
        return false;
    }
}
